package zserver

import (
	"fmt"
	"net"
	"zinx/utils"
	"zinx/zinterface"
)

type Zserver struct {
	Name      string // 服务器名称
	IP        string // 监听地址
	Port      int    // 监听端口
	IPVersion string // 监听方法

	// Router zinterface.IRouter // 路由
	// 修改为使用MsgHandler进行路由管理
	MsgHandler	zinterface.IMsgHandler
}

func (z *Zserver) Start() {
	fmt.Printf("[zinx]Server %s starting at\nHost: %s\nPost: %d\n",
		utils.GlobalObject.Name, utils.GlobalObject.Host, utils.GlobalObject.Port)
	fmt.Printf("Version: %s\nMaxConnection: %d\nMaxPackageSize: %d\n",
		utils.GlobalObject.Version, utils.GlobalObject.MaxConnection, utils.GlobalObject.MaxPackageSize)

	go func() {
		// 获取socket
		tcpAddr, err := net.ResolveTCPAddr(z.IPVersion, fmt.Sprintf("%s:%d", z.IP, z.Port))
		if err != nil {
			fmt.Println("ERROR ON START SERVER :", err)
			return
		}

		// 开始监听
		listenner, err := net.ListenTCP(z.IPVersion, tcpAddr)
		if err != nil {
			fmt.Println("ERROR ON LISTENNING ADDR: ", err)
			return
		}

		// 简单写个cid
		var cid uint32 = 0

		// 阻塞地等待客户端连接，处理客户端业务
		for {
			conn, err := listenner.AcceptTCP()
			if err != nil {
				fmt.Println("ERROR ON ACCEPT CLIENT: ", err)
				continue
			}

			dealConn := NewConnector(conn, cid, z.MsgHandler)
			cid++

			go dealConn.Start()
		}
	}()

}

func (z *Zserver) Stop() {

}

func (z *Zserver) Serve() {
	z.Start()

	select {}
}

// func (zs *Zserver) AddRouter(router zinterface.IRouter) {
// 	zs.Router = router
// }
// 0.6 版本修改为使用MsgHandler
func (zs *Zserver) AddRouter(msgId uint32, router zinterface.IRouter) {
	zs.MsgHandler.AddRouter(msgId, router)
}

func New(name string) zinterface.Zinterface {
	zs := &Zserver{
		Name:      utils.GlobalObject.Name,
		IP:        utils.GlobalObject.Host,
		Port:      utils.GlobalObject.Port,
		IPVersion: "tcp4",
		// Router:    nil, 0.6版本修改为使用MsgHandler
		MsgHandler: NewMsgHandler(),

	}

	return zs
}
